package cn.sh.yhk.acl;

import cn.sh.yhk.acl.mapper.RoleMapper;
import cn.sh.yhk.acl.mapper.UserMapper;
import cn.sh.yhk.acl.mapper.UserRoleMapper;
import cn.sh.yhk.acl.po.RolePo;
import cn.sh.yhk.acl.po.UserPo;
import cn.sh.yhk.acl.po.UserRolePo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname Yhk
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/10/2 16:44
 * @Created by y6522
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UserRoleMapper userRoleMapper;


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<UserPo> userQueryWrapper = new LambdaQueryWrapper();
        userQueryWrapper.eq(UserPo::getUsername, username);
        UserPo user = userMapper.selectOne(userQueryWrapper);


        UserDetailsInfo userDetailsInfo = new UserDetailsInfo();
        BeanUtils.copyProperties(user, userDetailsInfo);
        userDetailsInfo.setPassword(passwordEncoder.encode(userDetailsInfo.getPassword()));


        if (ObjectUtils.isEmpty(userDetailsInfo)) {
            throw new UsernameNotFoundException("用戶不存在");
        }

        LambdaQueryWrapper<UserRolePo> roleQueryWrapper = new LambdaQueryWrapper<>();
        roleQueryWrapper.eq(UserRolePo::getUid, user.getId());
        List<Integer> rids = userRoleMapper.selectList(roleQueryWrapper).stream()
                .map(UserRolePo::getRid).toList();


        LambdaQueryWrapper<RolePo> rQueryWrapper = new LambdaQueryWrapper<RolePo>()
                .in(RolePo::getId, rids);
        List<RolePo> roleList = roleMapper.selectList(rQueryWrapper);


        userDetailsInfo.setRole(roleList.stream().map(RolePo::getId)
                .map(String::valueOf).collect(Collectors.joining(",")));
        userDetailsInfo.setUserid(user.getId());
        log.info("spring security用户信息:{}", userDetailsInfo);
        return userDetailsInfo;
    }
}
